﻿@using Huirui.Cavan.Domain.MainBoundedContext.PurchaseModule
@model Huirui.Cavan.Presentation.ViewModel.PurchaseModule.IPayViewModel
@{
    Layout = null;
}
@using (Html.BeginForm(ActionConst.ADD, ControllerConst.PAY))
{
    <div class="tool_bar">
        <input id="pay_save" type="submit" style="display: none;" />
        <input id="pay_reset" type="reset" style="display: none" />
        <a href="#" class="easyui-linkbutton" data-options="plain:true,iconCls:'icon-save'"
            onclick="javascript:$('#pay_save').click()">保存</a>
        <a href="#" class="easyui-linkbutton" data-options="plain:true,iconCls:'icon-add'">新增</a>
        <a href="#" class="easyui-linkbutton" data-options="plain:true,iconCls:'icon-undo'"
            onclick="javascript:$('#pay_reset').click()">重置</a>
        <a href="#" class="easyui-linkbutton" data-options="plain:true,iconCls:'icon-delete'">删除</a>
        <a href="#" class="easyui-linkbutton" data-options="plain:true,iconCls:'icon-search'" onclick="addTab('支付列表','center_tt','@Url.Action(ActionConst.LIST, ControllerConst.PAY)')">查询</a>
        <a href="#" class="easyui-linkbutton" data-options="plain:true,iconCls:'icon-print'">打印</a>
        <a href="#" class="easyui-linkbutton" data-options="plain:true,iconCls:'icon-collapse'"
            onclick="toggleHeard()">折叠/展开</a>
    </div>
    
    <table class="form_heard">
        <tr>
            <td class="c100">
                <label>
                    付款日期:</label>
            </td>
            <td class="c160">
                @Html.TextBoxFor(m => m.Item.PayDate, new { id = "payDateForPay", style = "height:18px", @class = "Wdate", onfocus = "WdatePicker({minDate:'%y-%M-#{%d+1}'})" })
            </td>
            <td class="c100">
                <label>
                    付款单号:</label>
            </td>
            <td class="c160">
                @Html.TextBoxFor(m => m.Item.Id, new { id = "payCodeForPay" })
            </td>
            <td class="c100"></td>
        </tr>
        <tr>
            <td class="c100">
                <label>
                    供应商*:</label>
            </td>
            <td class="c160">
                @Html.TextBox("supplierCodeForPay", MyUtility.RemovePrefix(Model.Item.Supplier.Id), new { id = "supplierCodeWithNoPrefixForPay" })
                @Html.HiddenFor(m => m.Item.Supplier.Id, new { id = "supplierCodeForPay" })
            </td>
            <td colspan="2">
                @Html.TextBoxFor(m => m.Item.Supplier.Name, new { id = "supplierNameForPay" })
            </td>
            <td class="c100"></td>
        </tr>
        <tr>
            <td class="c100">
                <label>
                    账户:</label>
            </td>
            <td class="c160">
                @Html.TextBox("accountCodeWithNoPrefixForPay", MyUtility.RemovePrefix(Model.Item.FromAccount.Id), new { id = "accountCodeWithNoPrefixForPay" })
                @Html.HiddenFor(m => m.Item.FromAccount.Id, new { id = "accountCodeForPay" })
            </td>
            <td class="c100">
                <label>
                    支付号:</label>
            </td>
            <td class="c160">
                @Html.TextBoxFor(m => m.Item.AccountNumber, new { id = "accountNumberForPay" })
            </td>
            <td class="c100"></td>
        </tr>
        <tr>
            <td class="c100">
                <label>
                    币别:</label>
            </td>
            <td class="c160">
                @Html.DropDownList("currency", this.Model.Currencies, new { id = "currencyForPay" })
                @Html.HiddenFor(m => m.Item.Currency, new { id = "currencyValueForPay" })
            </td>
            <td class="c100">
                <label>
                    汇率:</label>
            </td>
            <td class="c160">
                @Html.TextBoxFor(m => m.Item.CurrencyRate, new { id = "currencyRateForPay" })
            </td>
            <td class="c100"></td>
        </tr>
        <tr>
            <td class="c100">
                <label>
                    付款金额:</label>
            </td>
            <td class="c160">
                @Html.TextBoxFor(m => m.Item.Amount, new { id = "amountForPay" })
            </td>
            <td class="c100">
                <label>
                    现金折扣:</label>
            </td>
            <td class="c160">
                @Html.TextBoxFor(m => m.Item.Discount, new { id = "discountForPay" })
            </td>
            <td class="c100"></td>
        </tr>
        <tr>
            <td class="c100">
                <label>
                    备注*:</label>
            </td>
            <td colspan="3">
                @Html.TextAreaFor(m => m.Item.Remark, new { id = "remarkForPay", cols = "80", rows = "2" })
            </td>
            <td class="c100">
                <a>请选择常用备注</a>
            </td>
        </tr>
    </table>
    @Html.HiddenFor(m => m.PayDetails, new { id = "payDetails" })
}

<div id="tt" class="easyui-tabs">
    <div title="本次核算" style="padding: 20px;">
        <div>
            @using (Html.BeginForm(ActionConst.LIST, ControllerConst.UNPAY))
            { 
                @Html.HiddenFor(m => m.UnPaySearch.SupplierCode, new { id = "searchsupplierCode" })
                @Html.TextBoxFor(m => m.UnPaySearch.StartDate, new { id = "searchstartDate" })
                @Html.TextBoxFor(m => m.UnPaySearch.EndDate, new { id = "searchendDate" })
                @Html.TextBoxFor(m => m.UnPaySearch.UnPayCode, new { id = "searchunpayCode" })
                <input type="submit" value="查询" id="searchUnPay" />
            }
        </div>
        <div class="tool_bar_grid">
            <a>待结算业务清单</a><span>|</span><input type="button" id="autoAllocate" value="自动分配" />|@Html.Raw("未核销金额:")@Html.TextBoxFor(m => m.UnPaid, new { id = "unCertificateAmount" }) |汇兑损益<input type="text" id="currencyLost" />
        </div>
        <table id="unpays">
        </table>
    </div>
    <div title="已核算清单" style="overflow: auto; padding: 20px;">
        <table id="paid">
        </table>
    </div>
</div>
@{ Html.RenderAction(ActionConst.SEARCH, ControllerConst.SUPPLIER, new { purpose = "ForPay" }); }
@{ Html.RenderAction(ActionConst.SEARCH, ControllerConst.ACCOUNT, new { purpose = "ForPay" }); }
<script type="text/javascript">
    $(function () {
        $('#unpays').datagrid({
            columns: [[
                { field: 'IsSelected', title: '选择', width: 60, checkbox: true },
                { field: 'Id', title: '', hidden: true },
                { field: 'Amount', title: '核销金额', width: 80, editor: { type: 'numberbox' } },
                { field: 'CertificateDate', title: '核销日期', width: 60, editor: { type: 'datebox' } },
                { field: 'UnPayType', title: '业务类型', width: 100 },
                { field: 'CreateDate', title: '业务日期', width: 100 },
                { field: 'UnPayCode', title: '单据编号', width: 80 },
                { field: 'Currency', title: '币别', width: 80 },
                { field: 'CurrencyRate', title: '汇率', width: 80 },
                { field: 'Cost', title: '应付金额', width: 80 },
                { field: 'LeftAmount', title: '应付余额', width: 80 }
            ]]
        });

        $('#paid').datagrid({
            columns: [[
                { field: 'IsSelected', title: '选择', width: 60, checkbox: true },
                { field: 'Id', title: '', hidden: true },
                { field: 'Amount', title: '核销金额', width: 80, editor: { type: 'numberbox' } },
                { field: 'CertificateDate', title: '核销日期', width: 60, editor: { type: 'datebox' } },
                { field: 'UnPayType', title: '业务类型', width: 100 },
                { field: 'CreateDate', title: '业务日期', width: 100 },
                { field: 'UnPayCode', title: '单据编号', width: 80 },
                { field: 'Currency', title: '币别', width: 80 },
                { field: 'CurrencyRate', title: '汇率', width: 80 },
                { field: 'PaidAmount', title: '累积支付金额', width: 80 }
            ]]
        });

        $("form[action^='/unpay/list']").submit(function () {
            $("#searchsupplierCode").val($("#supplierCodeForPay").val());
            if ($("#searchsupplierCode").val() === undefined || $("#searchsupplierCode").val() == '') {
                alert("请选择供应商");
                return false;
            }
            $.ajax({
                url: this.action,
                type: this.method,
                data: $(this).serialize(),
                success: function (result) {
                    if (result.total > 0) {
                        $('#unpays').datagrid({
                            data: result
                        });

                        var rows = $('#unpays').datagrid('getRows');
                        var amount = 0;
                        for (var i = 0; i < rows.length; i++) {
                            $('#unpays').datagrid('beginEdit', i);

                            var ed = $('#unpays').datagrid('getEditors', i);
                            for (var j = 0; j < ed.length; j++) {
                                var e = ed[j];
                                if (e.field == "Amount") {
                                    $(e.target).attr("selectedUnPayRowIndex", i);
                                    $(e.target).bind("click", function () {
                                        $('#unpays').datagrid('selectRow', $(this).attr("selectedUnPayRowIndex"));
                                    });
                                    $(e.target).bind("blur", function () {
                                        amount = $(this).val();
                                        currentIndex = $(this).attr("selectedUnPayRowIndex");
                                        currentRow = $('#unpays').datagrid('getSelections')[currentIndex];
                                        rowId = $(this).parents().filter("tr").filter("[datagrid-row-index=" + currentIndex + "]").attr("id");
                                        $("#" + rowId).find("td").each(function () {
                                            if ($(this).attr("field") == "LeftAmount") {
                                                $(this).find("div").html(amount - currentRow.Cost);
                                            }
                                        });
                                    })
                                }
                            }
                        }
                    }
                    else {
                        $('#unpays').datagrid('loadData', { total: 0, rows: [] });
                    }
                },
                error: function () {
                    alert('系统繁忙，请稍候再试');
                }
            })

            return false;
        });

        $("form[action^='/pay/add']").submit(function () {
            disableOrEnableEditPay(true);
            var rows = $('#unpays').datagrid('getRows');
            payDetails = "[";
            for (var i = 0; i < rows.length; i++) {
                $('#unpays').datagrid('endEdit', i);
                if (i == (rows.length - 1)) {
                    payDetails = payDetails + "{ \"UnPay\" : { \"Id\" : " + rows[i].Id + "}, \"Amount\" : " + rows[i].Amount + ", \"CertificateDate\" : \"" + rows[i].CertificateDate + "\" }";
                }
                else {
                    payDetails = payDetails + "{ \"UnPay\" : { \"Id\" : " + rows[i].Id + "}, \"Amount\" : " + rows[i].Amount + ", \"CertificateDate\" : \"" + rows[i].CertificateDate + "\" }" + ",";
                }
            }
            payDetails = payDetails + "]";
            $("#payDetails").val(payDetails);
            $.ajax({
                url: this.action,
                type: this.method,
                data: $(this).serialize(),
                success: function (data) {
                    if (data) {
                        alert(data.Messages[0]);
                        disableOrEnableEditPay(false);
                    }
                },
                error: function () {
                    alert('系统繁忙，请稍候再试');
                }
            })

            return false;
        });

        $("#autoAllocate").bind("click", function () {
            if ($("#amountForPay").val() == '') {
                return false;
            }
            var rows = $('#unpays').datagrid('getRows');
            var paidRows = $('#paid').datagrid('getRows');
            var rowId;
            var allocateAmount;
            var realAllocateAmount;
            var leftAmount = parseFloat($("#unCertificateAmount").val());
            for (var i = 0; i < rows.length; i++) {
                rowId = $(".datagrid-btable").find("tr").filter("[datagrid-row-index=" + i + "]").attr("id");
                $("#" + rowId).find("td").each(function () {
                    if ($(this).attr("field") == "Cost") {
                        allocateAmount = parseFloat($(this).find("div").html());
                        if (allocateAmount < 0) {
                            leftAmount += -allocateAmount;
                        }
                    }
                });
            }
            for (var i = 0; i < rows.length; i++) {
                $('#unpays').datagrid('selectRow', i);
                currentRow = $('#unpays').datagrid('getSelections')[i];
                rowId = $(".datagrid-btable").find("tr").filter("[datagrid-row-index=" + i + "]").attr("id");
                $("#" + rowId).find("td").each(function () {
                    if ($(this).attr("field") == "Cost") {
                        allocateAmount = parseFloat($(this).find("div").html());
                    }
                });

                $("#" + rowId).find("td").each(function () {
                    if ($(this).attr("field") == "Amount") {
                        if (allocateAmount < 0) {
                            $(this).find("input").val(allocateAmount);
                        }
                        else {
                            if (leftAmount >= allocateAmount) {
                                realAllocateAmount = allocateAmount;
                                $(this).find("input").val(allocateAmount);
                            }
                            else {
                                realAllocateAmount = leftAmount;
                                $(this).find("input").val(leftAmount);
                            }
                            leftAmount -= realAllocateAmount;
                        }
                    }
                    if ($(this).attr("field") == "LeftAmount") {
                        if (realAllocateAmount != 0)
                        {
                            $(this).find("div").html(allocateAmount - realAllocateAmount);
                        }
                    }
                });
            }
            return false;
        });

        $("#supplierCodeWithNoPrefixForPay").bind("click", function () {
            InitSelectSupplier('suppliersForPay');
            openWindow("selectSupplierWindowForPay");
        });

        $("#searchSupplierForPay").submit(function () {
            $.ajax({
                url: this.action,
                type: this.method,
                data: $(this).serialize(),
                success: function (result) {
                    if (result.total > 0) {
                        $('#suppliersForPay').datagrid({
                            data: result,
                            checkOnSelect: true,
                            selectOnCheck: true
                        });
                    }
                },
                error: function () {
                    alert('系统繁忙，请稍候再试');
                }
            })

            return false;
        });

        $("#doSelectSupplierForPay").bind("click", function () {
            var currentRow = $('#suppliersForPay').datagrid('getSelected');
            $("#supplierCodeWithNoPrefixForPay").val(currentRow.NoPrefixId);
            $("#supplierCodeForPay").val(currentRow.Id);
            $("#supplierNameForPay").val(currentRow.Name);
            $("#searchUnPay").click();
            closeWindow("selectSupplierWindowForPay");
        });

        $("select#currencyForPay").bind("change", function () {
            $("#currencyValueForPay").val($(this).find("option:selected").text());
            $("#currencyRateForPay").val($(this).val());
        });

        $("#accountCodeWithNoPrefixForPay").bind("click", function () {
            InitSelectAccount('accountsForPay');
            openWindow("selectAccountWindowForPay");
        });

        $("#searchAccountForPay").submit(function () {
            $.ajax({
                url: this.action,
                type: this.method,
                data: $(this).serialize(),
                success: function (result) {
                    if (result.total > 0) {
                        $('#accountsForPay').datagrid({
                            data: result,
                            checkOnSelect: true,
                            selectOnCheck: true
                        });
                    }
                },
                error: function () {
                    alert('系统繁忙，请稍候再试');
                }
            })

            return false;
        });

        $("#doSelectAccountForPay").bind("click", function () {
            var currentRow = $('#accountsForPay').datagrid('getSelected');
            $("#accountCodeWithNoPrefixForPay").val(currentRow.NoPrefixId);
            $("#accountCodeForPay").val(currentRow.Id);
            closeWindow("selectAccountWindowForPay");
        });

        function disableOrEnableEditPay(enbled)
        {
            $("input[id$='ForPay']").each(function (i, val) {
                if ($("#payCodeForPay").val().length > 0) {
                    if (enbled) {
                        $(this).removeAttr("disabled");
                    }
                    else {
                        $(this).attr("disabled", "disabled");
                    }
                }
            })
        }

        disableOrEnableEditPay(false);

        $.ajax({
            url: '/pay/paid/' + '@Model.Item.Id',
            type: 'Post',
            success: function (result) {
                if (result.total > 0) {
                    $('#paid').datagrid({
                        data: result
                    });
                }
            },
            error: function () {
                alert('系统繁忙，请稍候再试');
            }
        })
    });
</script>
